# -*- coding: utf-8 -*-
# 网络日历
# by kanghua 

import requests

# 打开url
def open_url(url):
	headers = {
		"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36"
		}

	try:
		response = requests.get(url, headers = headers)
		if response.status_code == 200:
			return response.text
		else :
			return None

	except requests.exceptions.RequestException as e:
		print("err: net can't reach!");
		return None

import json

# 日历字典
calendar = dict();

# 日历key： 2020-09-01
def ymd_key(y, m, d):
	key_str = "{}-{:0>2}-{:0>2}".format(y, m, d);
	return key_str;

# 通过url数据更新日历
def update_calendar(y, m):
	y_m_str = "{}年{}月".format(y, m);
	url = "http://opendata.baidu.com/api.php?query=" + y_m_str + "&resource_id=39043&format=json&tn=wisetpl"
	rx = open_url(url);
	if None == rx:
		return;
	days = json.loads(rx)["data"][0]["almanac"]

	for day in days:
		key = ymd_key(day["year"], day["month"], day["day"])
		calendar[key] = day;

	return;

# 检查某天是否在日历字典中
def chk_calendar(y, m, d):
	return ymd_key(y, m, d) in calendar;

# 获取某天的日历信息
def get_day(y, m, d):
	# 日历字典无缓存，通过网络刷新
	if False == chk_calendar(y, m, d):
		update_calendar(y, m);

	# 获取信息
	try:
		key = ymd_key(y, m, d);
		return calendar[key];
	except KeyError:
		print("err: 日期错误!")
		return None;

# 检查是否休息
def chk_rest(y, m, d):
	day = get_day(y, m, d);
	if day == None:
		return 0;

        if "status" in day :
                if type(day["status"]) == str :
                        return int(day["status"]);
                else :
                        return day["status"];
	elif day["cnDay"] == "六" or day["cnDay"] == "日" :
		return 1;

	return 0;

# 获取星期几 一、二、...六、日
def get_week(y, m, d):
	day = get_day(y, m, d);
	if day == None:
		return "None";

	return day["cnDay"];

# 计算闰年
def chk_leap_year(y):
	if (y % 100 != 0) and (y % 4 == 0):
		return True;
	elif (y % 400 == 0):	
		return True;
	else :
		return False;

# 计算某天往前往后i天
def day_by_index(y, m, d, i):
	day_num = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
	# 闰年2月29天
	if chk_leap_year(y) == True:
		day_num[1] += 1; 

	d = d + i;
	while ((d > day_num[m - 1]) or (d < 1)):
		# 天进位处理
		if (d > day_num[m - 1]):
			d = d - day_num[m - 1];
			m += 1;
		elif (d < 1):
			m -= 1;
			d = d + day_num[m - 1];

		# 月进位处理
		if (m > 12):
			m = 1;
			y += 1;
		elif (m < 1):
			m = 12;
			y -= 1;

	return y, m, d;

# 测试代码
if __name__ == '__main__':

	print(get_day(2021, 10, 1))
	print(get_day(2021, 10, 8))
	print(get_day(2022, 11, 31))
	print(get_day(2022, 3, 28))

	print(chk_rest(2021, 10, 1))
	print(chk_rest(2021, 10, 8))
	print(chk_rest(2022, 11, 31))
	print(chk_rest(2022, 3, 28))

	for i in range(0, 20):
		y, m, d = day_by_index(2021, 12, 20, i)
		day = get_day(y, m, d);
		print("{}-{}-{} \ravoid: {}, \rsuit: {}".format(day["year"], day["month"], day["day"], day["avoid"], day["suit"]));

	print(chk_leap_year(2004));
	print(chk_leap_year(1901));
	print(chk_leap_year(2000));
	print(chk_leap_year(1900));

	print(day_by_index(2021, 12, 20, -60));

	print(get_week(2022, 7, 23));
